package com.jingbit.ai.music;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.NonNull;

import com.jingbit.ai.utils.IMusicListener;
import com.jingbit.ai.utils.MediaUtil;
import com.jingbit.ai.utils.TTSUtil;
import com.google.gson.reflect.TypeToken;
import com.jingbit.ai.AIApp;
import com.jingbit.ai.bean.MusicInfo;
import com.jingbit.ai.entities.BaseInfo;
import com.jingbit.ai.helper.GJsonHelper;
import com.jingbit.ai.helper.Logger;
import com.jingbit.ai.okhttp.OKHttp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MusicService extends Service implements MediaPlayer.OnCompletionListener {
    public static final int MODE_SEQUENTIAL = 0; // 顺序播放
    public static final int MODE_SHUFFLE = 1; // 随机播放
    public static final int MODE_REPEAT_SINGLE = 2;// 单曲循环
    public static final int MODE_REPEAT_ALL = 3; // 全部循环
    private static final String MUSIC_LIST = "http://192.168.0.106:9999/getAll"; // 全部循环
    private static final String SPECIAL_CHARS = "@\\#\\$\\^&\\*\\(\\)_\\-\\+=~`\\|/\\{\\}\\【\\】"; // 指定要删除的特殊字符
    private final IBinder mBinder = new MusicBinder();

    private List<MusicInfo> musicList;
    private MediaPlayer mMediaPlayer;

    private volatile int mCurrentPosition = 0;
    private volatile int mPlayMode;


    public class MusicBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        musicList = new ArrayList<>();
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnCompletionListener(this);
        loadMusics();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            stop();
            mMediaPlayer.release();
        }
    }

    public void setMusicList(List<MusicInfo> musicList) {
        this.musicList = musicList;
        this.musicList = musicList == null ? new ArrayList<>() : musicList;
        mCurrentPosition = 0;
    }

    public Object searchMusic(String keyword, boolean path) {
        for (int i = 0; i < musicList.size(); i++) {
            MusicInfo music = musicList.get(i);
            if (music.getTitle().contains(keyword) || music.getStyle().contains(keyword) || music.getPath().contains(keyword) || music.getArtist().contains(keyword)) {
                if (path) return music.getPath();
                return i;
            }
        }
        if (path) return "";
        return -1;
    }

    public void play(int position) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (musicList.size() > 0 && position < musicList.size()) {
                        mCurrentPosition = position;
                        mMediaPlayer.reset();
                        mMediaPlayer.setDataSource(musicList.get(mCurrentPosition).getPath());
                        mMediaPlayer.prepare();
                        mMediaPlayer.start();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    play(position + 1);
                }
            }
        }).start();
    }

    public void playByRnd() {
        if (musicList.isEmpty()) {
            TTSUtil.doSpeak("音乐资源加载失败啦！");
            return;
        }
        mCurrentPosition = (int) (Math.random() * musicList.size());
        MusicInfo musicInfo = musicList.get(mCurrentPosition);
        String title = musicInfo.getTitle().replaceAll("[\\d" + SPECIAL_CHARS + "]", "")
                .replaceAll("\\s+", " ");
        TTSUtil.doSpeak("开始为你播放：" + title);
        play(mCurrentPosition);
    }

    public void pause() {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        }
    }

    public void stop() {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
    }

    public void next() {
        if (musicList.size() > 0) {
            mCurrentPosition++;
            if (mCurrentPosition >= musicList.size()) {
                mCurrentPosition = 0;
            }
            play(mCurrentPosition);
        }
    }

    public void previous() {
        if (musicList.size() > 0) {
            mCurrentPosition--;
            if (mCurrentPosition < 0) {
                mCurrentPosition = musicList.size() - 1;
            }
            play(mCurrentPosition);
        }
    }

    public int getCurrentPosition() {
        return mMediaPlayer.getCurrentPosition();
    }

    public int getDuration() {
        return mMediaPlayer.getDuration();
    }

    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }

    public void setPlayMode(int playMode) {
        mPlayMode = playMode;
    }

    public void onCompletion(MediaPlayer mediaPlayer) {
        switch (mPlayMode) {
            case MODE_SEQUENTIAL:
                next();
                break;
            case MODE_SHUFFLE:
                mCurrentPosition = (int) (Math.random() * musicList.size());
                play(mCurrentPosition);
                break;
            case MODE_REPEAT_SINGLE:
                play(mCurrentPosition);
            case MODE_REPEAT_ALL:
                next();
                break;
            default:
                break;
        }
    }

    public void loadMusics() {
        MediaUtil.loadMusics(this, new IMusicListener() {
            @Override
            public void onCompleted(List<MusicInfo> musicInfos) {
                setMusicList(musicInfos);
            }
        });
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                OKHttp.getInstance().get(MUSIC_LIST, null, new Callback() {
//
//                    @Override
//                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                        Logger.log(AIApp.TAG, "onResponse", response.code());
//                        if (response.code() == 200) {
//                            String json = response.body().string();
//                            BaseInfo baseInfo = GJsonHelper.parseJson(json, BaseInfo.class);
//                            if (baseInfo.getCode() == 0) {
////                                musicList = (ArrayList<MusicInfo>) JacksonHelper.jsonToList(baseInfo.getData().toString(), MusicInfo.class);
//                                json = GJsonHelper.toJson(baseInfo.getData());
//                                musicList = GJsonHelper.parseJsonArray(json, new TypeToken<List<MusicInfo>>() {
//                                }.getType());
//                                setMusicList(musicList);
//                            } else {
//                                TTSUtil.doSpeak("音乐资源加载失败啦！", true);
//                            }
//                        } else {
//                            TTSUtil.doSpeak("音乐资源加载失败啦！", true);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                        TTSUtil.doSpeak("音乐资源加载失败啦！", true);
//                    }
//                });
//            }
//        }).start();
    }

}
